package testProject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.onpositive.page.pagerendering.SiteContentRenderer;
import com.onpositive.storage.managers.UnifiedContentProvider;

@SuppressWarnings("serial")
public class StoredContentShowServlet extends HttpServlet {

	private static final SiteContentRenderer scr = (SiteContentRenderer) SiteContentRenderer
			.getSiteContentRenderer();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String reqURI = req.getRequestURI();
		if(reqURI.indexOf("/show") == 0){
			reqURI = reqURI.substring("/show".length());
		}	
		if (reqURI.indexOf(UnifiedContentProvider.RESOURCES_DIR) == -1 && !reqURI.endsWith(".html")) {
			resp.sendRedirect(reqURI);
		} else {
			String forDB = reqURI;
			// InputStream is =
			// UnifiedContentProvider.getContentElementAsStream(reqURI);
			byte[] arr = UnifiedContentProvider
					.getContentElementAsBytes(reqURI);
			String s = new String(arr, "UTF-8");
			if(reqURI.endsWith(".css")){
				s = "{{{\n" + "#!css" + s + "\n" + "}}}\n";
			}else if(reqURI.endsWith(".html")){
				s = "{{{\n" + "#!xml" + s + "\n" + "}}}\n";
			}	
			scr.initRenderer(getServletContext());
			scr.render(resp, new StringReader(s), forDB, true);
		}
	}
}
